<template>
    <div style="padding: 10px 50px 0; max-width: 550px">
        <el-form
            ref="pwdForm"
            :rules="pwdRules"
            :model="pwd"
            label-position="left"
            label-width="90px"
        >
            <el-divider content-position="left">修改密码</el-divider>
            <el-form-item label="当前密码" prop="prePass" style="margin-top: 35px">
                <el-input v-model="pwd.prePass" type="password" />
            </el-form-item>
            <el-form-item label="新密码" prop="newPass">
                <el-input v-model="pwd.newPass" type="password" />
            </el-form-item>
            <el-form-item v-if="displayCheckPwd" label="确认密码" prop="checkPass">
                <el-input v-model="pwd.checkPass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :disabled="!displayCheckPwd" @click="submitPwdForm">修改密码</el-button>
            </el-form-item>
        </el-form>
        <el-form
            ref="dataForm"
            v-loading="formLoading"
            :rules="dataRules"
            :model="user"
            label-position="left"
            label-width="90px"
            style="padding: 5px 0"
        >
            <el-divider content-position="left">密保信息</el-divider>
            <el-form-item label="密保问题" prop="question" style="margin-top: 35px">
                <el-input v-model="user.question" />
            </el-form-item>
            <el-form-item label="密保答案" prop="answer">
                <el-input v-model="user.answer" />
            </el-form-item>
            <el-divider content-position="left">基本信息</el-divider>
            <el-form-item label="用户名" prop="username" style="margin-top: 35px">
                <el-input v-model="user.username" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="user.email" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone" style="margin-bottom: 35px">
                <el-input v-model="user.phone" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitDataForm">更新信息</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { getInfo, updatePassword, updateUser } from '@/api/user'

export default {
    data() {
        var validatePwd = (rule, value, callback) => {
            // 如果第一次编辑密码的时候, 显示再次输入密码
            if (this.displayCheckPwd === false) {
                this.displayCheckPwd = true
            }
            // 基本验证
            if (value === '') {
                callback(new Error('请输入密码'))
            } else if (value.length < 6) {
                callback(new Error('密码不能小于6位'))
            } else {
                callback()
            }
        }
        var validatePwd2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.pwd.newPass) {
                callback(new Error('两次输入密码不一致!'))
            } else {
                callback()
            }
        }
        return {
            dialogFormVisible: false,
            displayCheckPwd: false,
            formLoading: false,
            pwd: {
                prePass: '',
                newPass: '',
                checkPass: ''
            },
            user: {
                id: undefined,
                username: '',
                email: '',
                phone: '',
                question: '',
                answer: '',
                role: undefined
            },
            pwdRules: {
                prePass: [
                    { validator: validatePwd, trigger: 'change' },
                    { required: true }
                ],
                newPass: [
                    { validator: validatePwd, trigger: 'change' },
                    { required: true }
                ],
                checkPass: [
                    { validator: validatePwd2, trigger: ['change', 'blur'] },
                    { required: true }
                ]
            },
            dataRules: {
                username: [{ required: true, message: '用户名不能为空', trigger: ['blur', 'change'] }],
                email: [{
                    required: true,
                    type: 'email',
                    message: '请输入正确的邮箱地址',
                    trigger: ['blur', 'change']
                }],
                phone: [{
                    required: true,
                    pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/,
                    message: '请输入正确的手机号或者座机号(区号-尾号)'
                }]
            }
        }
    },
    created() {
        this.getUserInfo()
    },
    methods: {
        async getUserInfo() {
            const user = await getInfo(this.$store.getters.token)
            delete user.createTime
            delete user.updateTime
            Object.assign(this.user, user)
        },
        submitDataForm() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    this.formLoading = true
                    const _data = Object.assign({}, this.user)
                    updateUser(_data).then(() => {
                        setTimeout(() => {
                            this.formLoading = false
                            this.$emit('updateUser', _data)
                            this.$message({
                                message: '信息更新成功',
                                type: 'success',
                                duration: 2000
                            })
                        }, 500)
                    }).catch(() => {
                        this.formLoading = false
                    })
                }
            })
        },
        submitPwdForm() {
            this.$refs['pwdForm'].validate((valid) => {
                if (valid) {
                    const _data = {
                        userid: Number(this.$store.getters.id),
                        passwd: this.pwd.prePass,
                        new_passwd: this.pwd.newPass
                    }
                    updatePassword(_data).then(async() => {
                        await this.$store.dispatch('user/logout')
                        this.$router.push(`/login?redirect=${this.$route.fullPath}`)
                        this.$message({
                            message: '密码修改成功, 请重新登录',
                            type: 'success',
                            duration: 2000
                        })
                    }).catch(() => {
                        this.pwd.prePass = ''
                    })
                }
            })
        }
    }
}
</script>
